package pl.edu.pw.elka.tinyrepo.gate.server;

import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;

import pl.edu.pw.elka.tinyrepo.common.HTTPHeaderType;
import pl.edu.pw.elka.tinyrepo.common.RequestHandler;
import pl.edu.pw.elka.tinyrepo.common.Response;
import pl.edu.pw.elka.tinyrepo.common.StatusCode;
import pl.edu.pw.elka.tinyrepo.common.exceptions.ContentAlreadyExistException;
import pl.edu.pw.elka.tinyrepo.common.exceptions.WrongPathException;
import pl.edu.pw.elka.tinyrepo.gate.descriptor.RepoDescriptor;


/**
 * @author: Kajot
 */

class MOVERequestHandler extends GateRequestHandler {
   
   public MOVERequestHandler(RepoDescriptor desc) {
      super(desc);
   }
   
   @Override
   public void run() {
	   
      OutputStream out = null;
      
      try { 
         out = incomming.getOutputStream(); 		// wyjscie do klienta
         String source = request.getPath(); 	// miejsce zrodlowe
         String destination = request.getHeader(HTTPHeaderType.DESTINATION);
         if(destination == null)
            throw new IllegalArgumentException("missed destination");
         desc.moveFileOrDirectoryDesc(source, destination); // przeniesienie pliku lub calego katalogu
         
         // dla pelnej zgodnosci z WebDAV, jezeli bedzie kiedys zaimplementowany LOCK, trzeba 
         // jeszcze tutaj tu uwzglednic MOVE na katalogu, oraz uwzględniać Multi-Status
         
         Response res = new Response(StatusCode.CREATED);
         res.addHeader(HTTPHeaderType.DESTINATION, destination); // naglowek Destination z nowym miejscem elementu
         res.write(out);
         System.out.println("Sent response: \n"+res);
         
      }
      catch (IllegalArgumentException e) {
         e.printStackTrace();
         Response rs = new Response(StatusCode.BAD_REQUEST);
         rs.write(out);
      }
      catch (ContentAlreadyExistException e) {
         e.printStackTrace();
         Response rs = new Response(StatusCode.CONFLICT);
         rs.write(out);
      }
      catch (WrongPathException e) {
         e.printStackTrace();
         Response rs = new Response(StatusCode.FORBIDDEN);
         rs.write(out);
      }
      catch (FileNotFoundException e) { // pliku nie ma
         e.printStackTrace();
         Response rs = new Response(StatusCode.FORBIDDEN);
         rs.write(out);
      }
      catch (IOException e) {
         e.printStackTrace();
      }
      // socket jest zamykany w klasach DAVServer
   }


   @Override
   public RequestHandler copy() {
      return new MOVERequestHandler(desc);
   }
   
   
}
